package com.hzj.fiter;

import cn.hutool.core.util.StrUtil;
import com.hzj.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class JwtAuthenticationFilter implements HandlerInterceptor {

    @Autowired
    JwtUtils jwtUtils;

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)throws Exception {

        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json; charset=utf-8");
        String jwt = request.getHeader(jwtUtils.getHeader());
        String servletPath = request.getServletPath();
        System.out.println(servletPath);
        System.out.println("jwt过滤器开启");
        System.out.println(jwt);
        if (!StrUtil.isBlankOrUndefined(jwt)) {
            Claims claims = jwtUtils.getClaimByToken(jwt);
            System.out.println(claims);
            if (claims == null){
                throw new JwtException("token 异常" );
            }
            if (!jwtUtils.isTokenExpired(claims)){
                throw new JwtException("token已过期");
            }
            System.out.println("通过拦截器");
            return true;
        }
        System.out.println("未通过拦截器");
        return false;
    }
}
